<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Providers\RouteServiceProvider;
use App\Models\User;
use App\Services\EmailVerificationService;
use Illuminate\Foundation\Auth\RegistersUsers;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Illuminate\Http\Request;
use Illuminate\Validation\ValidationException;
use Illuminate\Support\Facades\Log;

class RegisterController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Register Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles the registration of new users as well as their
    | validation and creation. By default this controller uses a trait to
    | provide this functionality without requiring any additional code.
    |
    */

    use RegistersUsers;

    /**
     * Where to redirect users after registration.
     *
     * @var string
     */
    protected $redirectTo = RouteServiceProvider::HOME;
    protected $verificationService;

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct(EmailVerificationService $verificationService)
    {
        $this->middleware('guest');
        $this->verificationService = $verificationService;
    }

    /**
     * Get a validator for an incoming registration request.
     *
     * @param  array  $data
     * @return \Illuminate\Contracts\Validation\Validator
     */
    protected function validator(array $data)
    {
        return Validator::make($data, [
            'name' => ['required', 'string', 'max:255'],
            'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
            'password' => ['required', 'string', 'min:8', 'confirmed'],
            'captcha' => ['required', 'string'],
        ]);
    }

    public function sendVerificationCode(Request $request)
    {
        try {
            Log::info('Sending verification code request received', ['email' => $request->email]);
            
            // 验证邮箱格式和唯一性
            $request->validate([
                'email' => ['required', 'email', 'unique:users']
            ]);

            // 检查是否已经发送过验证码且未过期
            $existingCode = \App\Models\EmailVerificationCode::where('email', $request->email)
                ->where('expires_at', '>', now())
                ->first();

            if ($existingCode) {
                return response()->json([
                    'message' => '验证码已发送，请查看您的邮箱',
                    'status' => 'success'
                ]);
            }

            $result = $this->verificationService->sendVerificationCode($request->email);
            
            Log::info('Verification code sent successfully', ['email' => $request->email]);
            
            return response()->json([
                'message' => '验证码已发送到您的邮箱',
                'status' => 'success'
            ]);
        } catch (\Illuminate\Validation\ValidationException $e) {
            Log::error('Validation error', [
                'email' => $request->email,
                'errors' => $e->errors()
            ]);
            
            return response()->json([
                'message' => $e->getMessage(),
                'errors' => $e->errors(),
                'status' => 'error'
            ], 422);
        } catch (\Exception $e) {
            Log::error('Error sending verification code', [
                'email' => $request->email,
                'error' => $e->getMessage()
            ]);
            
            return response()->json([
                'message' => '发送验证码失败：' . $e->getMessage(),
                'status' => 'error'
            ], 500);
        }
    }

    /**
     * Create a new user instance after a valid registration.
     *
     * @param  array  $data
     * @return \App\Models\User
     */
    protected function create(array $data)
    {
        // 验证验证码
        if (!$this->verificationService->verifyCode($data['email'], $data['captcha'])) {
            throw ValidationException::withMessages([
                'captcha' => ['验证码无效或已过期'],
            ]);
        }

        return User::create([
            'name' => $data['name'],
            'email' => $data['email'],
            'password' => Hash::make($data['password']),
        ]);
    }
}
